package com.je.meta.service;

import com.je.auth.check.SystemVariablesInterface;
import com.je.auth.check.context.model.AuthRequest;
import com.je.common.base.entity.func.FuncInfo;
import com.je.common.base.service.rpc.FunInfoRpcService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.provider.pojo.RpcReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SystemVariablesInterfaceImpl implements SystemVariablesInterface {

    @RpcReference(microserviceName = "meta", schemaId = "systemVariableRpcService")
    private SystemVariableRpcService systemVariableRpcService;
    @RpcReference(microserviceName = "meta", schemaId = "metaFuncInfoRpcService")
    private FunInfoRpcService funInfoRpcService;

    @Override
    public Map<String, String> getSystemVariablesByCodes(String[] codes) {
        Map<String, String> resultMap = new HashMap<>();
        Map<String, Object> backVar = systemVariableRpcService.formatCurrentUserAndCachedVariables();
        for (String code : codes) {
            resultMap.put(code, backVar.get(code) == null ? "" : backVar.get(code).toString());
        }
        return resultMap;
    }

    @Override
    public String getRequestFormData(AuthRequest authRequest, String code) {
        if (authRequest.getSource() instanceof Invocation) {
            Invocation invocation = (Invocation) authRequest.getSource();
            return invocation.getRequestEx().getParameter(code);
        }
        return "";
    }

    @Override
    public String getRequestHeaderData(AuthRequest authRequest, String code) {
        if (authRequest.getSource() instanceof Invocation) {
            Invocation invocation = (Invocation) authRequest.getSource();
            if (code.equals("pd")) {
                return invocation.getSchemaMeta().getMicroserviceName();
            }
            return invocation.getRequestEx().getHeader(code);
        }
        return "";
    }

    @Override
    public List<String> getChildFuncCodesByFuncCode(String funcCode) {
        FuncInfo funcInfo = funInfoRpcService.getFuncInfo(funcCode);
        if (funcInfo == null) {
            return new ArrayList<>();
        }
        if (funcInfo.getFuncSubsetIdList() == null) {
            return new ArrayList<>();
        }
        return funcInfo.getFuncSubsetIdList();
    }

}
